package com.wenkang.stu.config.security.filter;

import com.wenkang.stu.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 自定义验证过滤器（Validation：确认；批准；生效）
public class JwtValidationFilter extends BasicAuthenticationFilter {
    private static final String AUTHENTICATION_PREFIX = "Bearer ";

    public JwtValidationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 拦截请求
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String bearerAuthentication = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isNotBlank(bearerAuthentication) && bearerAuthentication.startsWith(AUTHENTICATION_PREFIX)) {
            SecurityContextHolder.getContext().setAuthentication(setAuthentication(bearerAuthentication));
        }
        super.doFilterInternal(request, response, chain);
    }

    // 验证token
    private Authentication setAuthentication(String bearerAuthentication) {
        String jwtToken = bearerAuthentication.replace(AUTHENTICATION_PREFIX, "");
        String username = JwtUtils.getUsername(jwtToken);
        if (StringUtils.isNotBlank(username)) {
            // 解析权限列表
            List<SimpleGrantedAuthority> authorities = JwtUtils.getAuthorities(jwtToken);
            return new UsernamePasswordAuthenticationToken(username, null, authorities);
        }
        return null;
    }
}
